package leetcode.code0219;

import java.util.HashSet;
import java.util.Set;

import leetcode.IDebug;
import leetcode.helper.HelpDebug;

//执行用时：18 ms, 在所有 Java 提交中击败了90.50%的用户
//
//内存消耗：53.2 MB, 在所有 Java 提交中击败了6.57%的用户
//
//通过测试用例：51 / 51
public class Solution implements IDebug {

	public boolean containsNearbyDuplicate(int[] nums, int k) {
		int len = nums.length;
		if (len < 2)
			return false;
		int r = 1;
		Set<Integer> set = new HashSet<>();
		set.add(nums[0]);
		int cur = 0;
		while (r <= k && r < len) {// k+1的窗口 && 窗口可能大于整个数组
			if (set.contains(cur = nums[r++])) {
				return true;// 有就结束
			}
			set.add(cur);// 没有继续
		}
		int l = 0;
		while (r < len) {// 不越界
			set.remove(nums[l++]);// 出窗
			if (set.contains(cur = nums[r++])) {
				return true;
			}
			set.add(cur);
		}
		return false;
	}

	@Override
	public void debug1() {
		HelpDebug.compare(true, this.containsNearbyDuplicate(HelpDebug.str2array3("[1,2,3,1]"), 3));
	}

	@Override
	public void debug2() {
		HelpDebug.compare(true, this.containsNearbyDuplicate(HelpDebug.str2array3("[1,0,1,1]"), 1));
	}

	@Override
	public void debug3() {
		HelpDebug.compare(false, this.containsNearbyDuplicate(HelpDebug.str2array3("[1,2,3,1,2,3]"), 2));
	}

	@Override
	public void debug4() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		Solution so = new Solution();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();

	}

}
